﻿using BCCommon;
using BCData.TMS.MarketingCoupon.MarketingCouponUsing;
using BCDto.TMS.MarketingCoupon.MarketingCouponUsing;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;

namespace BCService.TMS.MarketingCoupon.MarketingCouponUsing
{
    public class MarketingCouponUsingService : IMarketingCouponUsingService
    {
        private readonly IMarketingCouponUsingData marketingCouponUsingData;
        private readonly IRedisService redisService;
        private readonly string key = string.Format("{0}", EntityNameConst.MarketingCouponUsingEntity);
        public MarketingCouponUsingService(
            IMarketingCouponUsingData marketingCouponUsingData,
            IRedisService redisService)
        {
            this.marketingCouponUsingData = marketingCouponUsingData;
            this.redisService = redisService;
        }
        public PageableList<MarketingCouponUsingDto> Query(
            long? marketingCouponTypeId, long? userId, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key,marketingCouponTypeId, userId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (list, count) = this.marketingCouponUsingData.Query(marketingCouponTypeId, userId, pageIndex, pageSize).Result;
                return new PageableList<MarketingCouponUsingDto>
                {
                    Items = list.As<IEnumerable<MarketingCouponUsingDto>>(),
                    Count = count,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromDays(1));
            return result;
        }
        public MarketingCouponUsingDto GetSingle(long marketingCouponUsingId)
        {
            string cacheKey = this.redisService.GetKey(key, marketingCouponUsingId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var entity= this.marketingCouponUsingData.GetSingle(marketingCouponUsingId).Result;
                return entity;
            }, TimeSpan.FromDays(1));
            return result.As<MarketingCouponUsingDto>();
        }

        public bool Exists(long marketingCouponId)
        {
            return this.marketingCouponUsingData.Exists(marketingCouponId).GetAwaiter().GetResult();
        }
    }
}
